#include "getpost.h"

GetPost::GetPost(QObject *parent) : QObject(parent)
{
    socket = new QTcpSocket(this);

    connect(socket, &QTcpSocket::connected, this, &GetPost::connected);
    connect(socket, &QTcpSocket::disconnected, this, &GetPost::disconnected);
    connect(socket, &QTcpSocket::readyRead, this, &GetPost::onReadyRead);
    connect(socket, QOverload<QAbstractSocket::SocketError>::of(&QTcpSocket::error),
            this, &GetPost::onError);
}

void GetPost::connectToServer(const QString &host, quint16 port)
{
    socket->connectToHost(host, port);
}

void GetPost::sendMessage(const QString &message)
{
    if (socket->state() == QTcpSocket::ConnectedState)
    {
        socket->write(message.toUtf8());
        emit messageSent();
    }
    else
    {
        emit errorOccurred("未连接到服务器，无法发送消息");
    }
}

void GetPost::onReadyRead()
{
    QString message = QString::fromUtf8(socket->readAll());
    emit messageReceived(message);
}

void GetPost::onError(QAbstractSocket::SocketError socketError)
{
    emit errorOccurred(socket->errorString());
}
